<?php

 class html_form
 {
        private $tbl = null;
        private $name = null;
        private $form_is_open = false;
        public $formdata = null;
        private $pages = Array();
        public $pageindex = 1;
        private $identificators = Array();
        
        function __construct($formName, $method = 'post', $action = null, $onSubmit = null, $pageindex = null)
        {
            ob_start();
            if(is_null($action))
            {
                $action = $_SERVER['REQUEST_URI'];
            }
            $this->name = $formName;
            $method = strtolower($method);
            $pageindexFieldname = $formName.'_pageindex';
            switch($method)
            {
                case 'post':
                    if(isset($_POST[$formName]))
                    {
                        $this->formdata = $_POST[$formName];
                    }
                    break;
                case 'get':
                    if(isset($_GET[$formName]))
                    {
                        $this->formdata = $_GET[$formName];
                    }
                    break;
            }
            if(!is_null($this->formdata))
            {
                if(isset($this->formdata[$pageindexFieldname]))
                {
                    if(is_numeric($this->formdata[$pageindexFieldname]))
                    {
                        $this->pageindex = 1+(int)$this->formdata[$pageindexFieldname];
                        if($this->pageindex<1){$this->pageindex=1;}
                    }
                }
            }
            if(!is_null($onSubmit))
            {
                $onSubmit = "onsubmit=\"$onSubmit\"";
            }
            $this->form_is_open = true;
            $form_id_attribute = is_null($formName) ? null : sprintf('id="%s"', $formName);
            ?><form <?php echo $form_id_attribute; ?> action="<?php echo $action; ?>" method="<?php echo $method; ?>" <?php echo $onSubmit; ?>>
            <?php
            if(is_numeric($pageindex))
            {
                $this->pageindex = (int)$pageindex;
            }
        }
        function end($destroy = false)
        {
            if(!$this->form_is_open)
            {
                return false;
            }
            $pageindexFieldname = $this->name.'_pageindex';
            ?>
            <div><input type="hidden" name="<?php echo $this->name."[$pageindexFieldname]"; ?>" value="<?php echo $this->pageindex; ?>" /></div>
            </form><?php
            $out = ob_get_clean();
            if(!$destroy)
            {
                echo $out;
            }
            return true;
        }
        // Добавление кнопки отправки данных
        function addSubmit($ControlName, $caption, $enabled = true)
        {
            if(!$this->form_is_open)
            {
                return false;
            }
            //$this->tbl->newcol();
            //$this->tbl->newcol();
            $ControlName = $this->name."[$ControlName]";
            $enabled = $enabled?null:' disabled';
            echo "<input type=\"submit\"$enabled value=\"$caption\" name=\"$ControlName\" />";
            return true;
        }
        
        // Добавление поля
        function addTextBox($pageindex = 1, $ControlName, $label=null, $hidden = false,
            $value = null, $disabled = false, $cols = 64, $rows=8)
        {
            if($pageindex != $this->pageindex)
            {
                return false;
            }
            if(!$this->form_is_open)
            {
                return false;
            }
            $ControlName = $this->name."[$ControlName]";
            if($hidden){$type = 'hidden';}
            if(!is_null($label)){echo $label;}
            if($disabled){$disabled = 'disabled';}else{$disabled=null;}
            echo sprintf('<textarea cols="%s" rows="%s" %s name="%s">%s</textarea>', $cols, $rows, $disabled, $ControlName, $value);
            return true;
        }
 
        function AddCaptcha($name, $color = '230_230_230')
        {
            $tab2 = new html_table(2, null, null, 4);
                $tab2->newcol(null, false, null, null, null, '10%');
                    echo sprintf('<img src="/mikron/captcha/captcha.php?rgb=%s" />', $color);
                $tab2->newcol();
                    $this->addInput(1, $name, null, 5, 5);
                $tab2->newcol(null, true, false, null, 'hiddentext', null, null, null, 2);
                    echo 'Введите код указанный на картинке';
            $tab2->end();
        }

        // Добавление поля
        function addInput($pageindex = 1, $ControlName, $label=null, $size=null, $maxlength=null, $hidden = false,
            $value = null, $disabled = false, $type = 'text', $id = null, $multipleCode = null)
        {
            if($pageindex != $this->pageindex)
            {
                return false;
            }
            if(!$this->form_is_open)
            {
                return false;
            }
            $size = (int)$size;
            if($size<1){$size=null;}
            $maxlength = (int)$maxlength;
            if($maxlength>0){$maxlength="maxlength=\"$maxlength\"";}else{$maxlength=null;}
            $ControlName = $this->name."[$ControlName]";
            if(!is_null($multipleCode))
            {
                $ControlName .= "[$multipleCode]";
            }
            if($hidden){$type = 'hidden';}
            if(!is_null($label)){echo $label;}
            if(!is_null($value))
            {$value="value=\"$value\"";}
            if($disabled){$disabled = 'disabled';}else{$disabled = null;}
            if(!is_null($id)){$id = sprintf('id="%s"', $id);}
            echo "<input type=\"$type\" $disabled size=\"$size\" $id $maxlength name=\"$ControlName\" $value />";
            return true;
        }
        
         // Добавление поля
        function addFile($pageindex = 1, $ControlName, $label=null, $disabled = false)
        {
            if($pageindex != $this->pageindex)
            {
                return false;
            }
            if(!$this->form_is_open)
            {
                return false;
            }
            $ControlName = $this->name."[$ControlName]";
            $type = 'file';
            if(!is_null($label)){echo $label;}
            if($disabled){$disabled = 'disabled';}else{$disabled = null;}
            echo "<input type=\"$type\" $disabled />";
            return true;
        }
 
         // Добавление чекбокса (поел с галочкой)
        function addRadio($pageindex = 1, $ControlName, $label=null, $onclick = null, $value = null, $onblur = null, $checked = false)
        {
            if($pageindex != $this->pageindex)
            {
                return false;
            }
            if(!$this->form_is_open)
            {
                return false;
            }
            $ControlName = $this->name."[$ControlName]";
            if(!is_null($onclick))
            {
                $onclick = "onclick=\"$onclick\"";
            }
            if(!is_null($onblur))
            {
                $onblur = "onchecked=\"$onblur\"";
            }
            if($checked)
            {
                $checked = "checked=\"checked\"";
            }
            $value2 = htmlspecialchars($value);
            echo sprintf('<input type="radio" %s name="%s" id="%s" %s %s value="%s" /> <label for="%s">%s</label>',
                $checked, $ControlName, $ControlName, $onclick, $onblur, $value2, $ControlName, $label);
            return true;
        }
 
         // Добавление чекбокса (поле с галочкой)
        function addCheckbox($pageindex = 1, $ControlName, $label=null, $onclick=null, $checked = false, $multiple_code = null)
        {
            if($pageindex != $this->pageindex)
            {
                return false;
            }
            if(!$this->form_is_open)
            {
                return false;
            }
            //$this->tbl->newcol($label);
            //$this->tbl->newcol();
            $ControlName = $this->name."[$ControlName]";
            if(!is_null($multiple_code))
            {
                $ControlName .= "[$multiple_code]";                
            }
            if(!is_null($onclick))
            {
                $onclick = "onclick=\"$onclick\"";
            }
            $tag_attributes = Array();
            $tag_attributes['type'] = 'checkbox';
            $tag_attributes['name'] = $ControlName;
            if($checked)
            {
                $tag_attributes['checked'] = 'checked';
            }
            $checked = $checked?' checked="checked"':null;
            echo MikronString::MakeTag('input', $tag_attributes, $onclick);
            return true;
        }

        public static function CreateSelectControlForEnumerator($ControlName, $items, $value = null)
        {
            ?><select name="<?php echo $ControlName; ?>"><?php
            foreach($items as $item)
            {
                $selected = ($value == $item['value'])?' selected ':null;
                ?><option <?php echo $selected; ?>value="<?php echo $item['value']; ?>"><?php echo $item['description']; ?></option><?php
            }
            ?></select><?php
        }

        public static function CreateSelectControlForArray($ControlName, $items, $value = null)
        {
            $enabled = count($items) > 0;
            $enabled = $enabled?null:' disabled';
            ?><select<?php echo $enabled;?> name="<?php echo $ControlName; ?>"><?php
            foreach($items as $editor_key => $editor_value)
            {
                ?><option <?php if($value == $editor_value){echo 'selected';} ?> value="<?php echo $editor_value; ?>"><?php echo $editor_key; ?></option><?php
            }
            ?></select><?php
        }
 
        public static function CreateSelectControlForEntity($ControlName, $entity_name, $value = null)
        {
            if(is_object($value) && !$value->isNew)
            {
                $value = $value->id;                
            }
            ?><select name="<?php echo $ControlName; ?>">
            <option value=""></option>
            <?php
            global $mikron;
            $items = $mikron->EntityManager->QueryDisplayNames($entity_name);
            foreach($items as $item)
            {
                $item_id = $item['id'];
                $title = $item['displayname'];
                $selected = $item_id == $value ? ' selected': null;
                ?><option<?php echo $selected;?> value="<?php echo $item_id; ?>"><?php echo $title; ?></option><?php
            }
            ?></select><?php
        }

        // Вставка контрола SELECT с заполнением данных из справочника
        function addSelectControlFromEnumerator($pageindex = 1, $ControlName, $label, $items, $value = null)
        {
            if($pageindex != $this->pageindex)
            {
                return false;
            }
            if(!$this->form_is_open)
            {
                return false;
            }
            $ControlName = $this->name."[$ControlName]";
            html_form::CreateSelectControlForEnumerator($ControlName, $items, $value);
            return true;
        }
        
        private function getId($controlName)
        {
            if(array_key_exists($controlName, $this->identificators))
            {
                return $this->identificators[$controlName];
            }
            else
            {
                $controlId = 'id'.md5(time().mt_rand(0, 999999).$controlName);
                $this->identificators[$controlName] = $controlId;
                return $controlId;
            }
        }

        // Вставка контрола SELECT с заполнением данных из сущности
        function addSelectControlFromEntity($pageindex = 1, $ControlName, $label, $entities, $value = null, $another_select_autofill = Array(), $nullValueItem = null)
        {
            $pageindex = (int)$pageindex;
            if($pageindex != $this->pageindex)
            {
                return false;
            }
            if(!$this->form_is_open)
            {
                return false;
            }
            $controlId = $this->getId($ControlName);
            $ControlName = $this->name."[$ControlName]";
            $on_change = null;
            if(is_array($another_select_autofill))
            {
                if(array_key_exists('fieldname', $another_select_autofill) && array_key_exists('sourcefile', $another_select_autofill))
                {
                    $targetName = $another_select_autofill['fieldname'];
                    $sourceFile= $another_select_autofill['sourcefile'];
                    $targetId = $this->getId($targetName);
                    $address = null;
                    ?>
                    <script type="text/javascript">
                        $(document).ready(function(){
                            var controlID = '#<?php echo $controlId; ?>';
                            $(controlID).change(function() 
                            {
                                var targetID = '#<?php echo $targetId; ?>';
                                var sourceFile = '<?php echo $sourceFile; ?>';
                                $.mikron.select(targetID).clear();
                                $(controlID).attr('disabled', true);
                                $(targetID).attr('disabled', true);
                                sourceFile = sourceFile.replace('{1}', $.mikron.select(controlID).value())
                                $(targetID).load(sourceFile, function()
                                    {
                                        $(controlID).attr('disabled', false);
                                        $(targetID).attr('disabled', false);
                                    });
                                
                            }); 
                        });
                    </script>
                    <?php
                }
            }
            $disabledControl = $entities->count() == 0;
            ?><select<?php if($disabledControl){echo ' disabled="disabled"';} ?> id="<?php echo $controlId; ?>" name="<?php echo $ControlName; ?>"><?php
            if(!is_null($nullValueItem))
            {
                if($value === null)
                {
                    echo sprintf('<option value="" class="stealth_text">%s</option>', $nullValueItem);
                }
            }
            global $mikron;
            // $items = $mikron->Enumerators->getEnum($enumName);
            while($item = $entities->fetch())
            {
                $selected = $value == $item->id ? ' selected="selected"' : null;
                ?><option<?php echo $selected;?> value="<?php echo $item->id; ?>"><?php echo $item->DisplayName(); ?></option><?php
            }
            ?></select><?php
            return true;
        }
        function addSelectControlFromArray($pageindex = 1, $ControlName, $label, $size = null, $entities, $value = null)
        {
            if($pageindex != $this->pageindex)
            {
                return false;
            }
            if(!$this->form_is_open)
            {
                return false;
            }
            $ControlName = $this->name."[$ControlName]";
            ?><select name="<?php echo $ControlName; ?>"><?php
            global $mikron;
            foreach($entities as $item)
            {
                $item_id = $item['id'];
                $item_displayname = $item['displayname'];
                if(!is_string($item_id))
                {
                    $item_id = -1;
                }
                if(!is_string($item_displayname))
                {
                    $item_displayname = '...';
                }
                $selected = ($value == $item_id)?' selected="selected"':null;
                echo sprintf('<option%s value="%s">%s</option>', $selected, $item_id, $item_displayname);
            }
            ?></select><?php
            return true;
        }
    }
    
?>